﻿using RFIDData.Data;
using RFIDData.Models;
using StudyKitLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Phoenix_RFID2
{
	public partial class Form1 : Form
	{
		private int emNo = -1;

		private string uid;

		Dbman dm = new Dbman();

		RFIDDB context = new RFIDDB();


		public Form1()
		{
			InitializeComponent();
			//for (int i = 1; i < 11; i++)    // COM1~10            
			//    cmbPort.Items.Add("COM" + i.ToString());
			//cmbPort.SelectedIndex = 0;
			//lblTimer.Text = DateTime.Now.ToString("HH:mm:ss");

			timer2.Enabled = true;

		}


		private void timer2_Tick(object sender, EventArgs e)
		{
			lblTimer.Text = DateTime.Now.ToString("yy년 MM월 dd일 HH:mm:ss tt");

		}


		public static RF1356.REPLY reply; // 리턴 상태를 반환하는 변수
		public static long PortNO;		  // 시리얼 포트 번호 
		public string UID;
		private void btnIn_Click(object sender, EventArgs e)
		{
			if (emNo == -1)
			{
				MessageBox.Show("카드가 인식되지 않았습니다");

				return;
			}
			//이 곳에서 DB에 입력해주는 것 출근을 누르면 출근시간 값이 저장되게 하는.

			//PRFID

			DialogResult dialogResult = MessageBox.Show("출근하시겠습니까?", "카드 등록", MessageBoxButtons.YesNo);
			if (dialogResult == DialogResult.Yes)
			{

				// if(
				var k = context.Commutes.Where(c => c.Ymd == DateTime.Today && c.EmNo == emNo);

				if (k.Count() == 0)
				{
					Commute commute = new Commute
					{
						//CoNo = context.Commute
						EmNo = emNo,
						InTime = DateTime.Now,
						Ymd = DateTime.Today

					};
					dm.CommuteAdd(commute);

				}
				else
				{
					MessageBox.Show("이미 출근 처리가 되었습니다.");
				}


			}
			else if (dialogResult == DialogResult.No)
			{
				this.Close();
			}
		}





		private void chkServerChecked(object sender, EventArgs e)
		{

			if (chkServer.Checked)
			{

				timer1.Enabled = true;

				//btnRead.Enabled = false;
				btnIn.Enabled = true;
				btnOut.Enabled = true;



			}
			else
			{
				timer1.Enabled = false;

				//btnRead.Enabled = true;
				btnIn.Enabled = false;
				btnOut.Enabled = false;
			}
		}

		private void btnOpenPort_Click(object sender, EventArgs e)
		{
			try
			{
				for (int port = 1; port < 11; port++)
				{
					RF1356.RFReaderOpen(port);

					reply = RF1356.BaudDetec(port);

					if (reply == RF1356.REPLY.RF_OK)
					{
						PortNO = port;
						//MessageBox.Show("성공");
						break;
					}
				}

				if (reply != RF1356.REPLY.RF_OK)
					MessageBox.Show("COM Port Open Fail", "Error",
								MessageBoxButtons.OK,
								MessageBoxIcon.Exclamation,
								MessageBoxDefaultButton.Button1);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}



		}

		private void btnOut_Click(object sender, EventArgs e)
		{
			if (emNo == -1)
			{
				MessageBox.Show("카드가 인식되지 않았습니다");

				return;
			}

			DialogResult dialogResult = MessageBox.Show("퇴근하시겠습니까?", "카드 등록", MessageBoxButtons.YesNo);
			if (dialogResult == DialogResult.Yes)
			{

				var k = context.Commutes.Where(c => c.Ymd == DateTime.Today && c.EmNo == emNo);

				if (k.Count() == 0)
				{

					MessageBox.Show("출근부터 해주세요");

				}
				else
				{

					Commute a = k.First();

					a.OutTime = DateTime.Now;

					context.SaveChanges();

				}
			}


			else if (dialogResult == DialogResult.No)
			{
				this.Close();
			}
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			int tagCnt = 0;
			string SerialNumbers = String.Empty;
			string UID = String.Empty;		 //이 부분에서 UID를 입력해 주는 것이 필요함


			reply = RF1356.RFReadSerialNO(PortNO, ref SerialNumbers);//9


			switch (reply)
			{
				case RF1356.REPLY.RF_OK:
					tagCnt = int.Parse(SerialNumbers.Substring(0, 2));

					for (int i = 0; i < tagCnt; i++)
					{
						string str = SerialNumbers.Substring(2 + (16 * i), 16);//9
																			   //string UID = String.Empty;


						for (int j = 0; j < 8; j++)
						{
							UID = str.Substring(2 * j, 2) + UID;//9
						}

					}

					if (uid == UID)
					{
						break;
					}

					uid = UID;


					//MessageBox.Show(UID);

					var kk = context.Cards.Where(c => c.CaNo == UID).Select(c => c.EmNo);
					if (kk.Count() > 0)
					{
						emNo = (int)kk.First();

						var kk2 = context.Employees.Where(d => d.EmNo == emNo).Select(d => d.Name).Single();
						txtName.Text = kk2;
						txtInOutTime.Text = lblTimer.Text;

						byte[] buffer = (byte[])context.Employees.Where(p => p.EmNo == emNo).Select(p => p.Image).Single();
						MemoryStream stream = new MemoryStream(buffer);
						pbEmployee.Image = Image.FromStream(stream);
						stream.Close();

					}
					break;

				case RF1356.REPLY.NO_TRANSPONDER:
					txtName.Text = string.Empty;
					txtInOutTime.Text = string.Empty;
					emNo = -1;
					uid = null;
					//MessageBox.Show("연결 안 됨");
					break;

				case RF1356.REPLY.RF_ERR:
					MessageBox.Show("오류");
					break;

				default:
					break;
			}

		}
	}
}
